package com.cm309.hospital.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import com.cm309.hospital.model.Booking;

public class BookingDao {
	public static MyDataSource mds = new MyDataSource();
	
	public boolean add(Booking booking) {
		boolean result = false;
		try {
			Connection conn = mds.getConnection();
			PreparedStatement ps = null;
			
			
			try {
				ps = conn.prepareStatement("INSERT INTO BOOKING (doctor_schedule_id, patient_id, status) VALUES (?, ?, ?)");
				ps.setInt(1, booking.getDoctor_schedule_id());
				ps.setInt(2, booking.getPatient_id());
				ps.setString(3, "A");
				ps.execute();
				result = true;
			} finally {
				ps.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
		
	}

	public int getNextTicketNum(String subject_id,String doctor_id,Date booking_date,String am_pm_ind) {
		int next_ticket_num =1 ;
		try {
			Connection conn = mds.getConnection();
			PreparedStatement ps = null;
			try {
				ps = conn.prepareStatement("SELECT max(ticket_id) as max_ticket FROM BOOKING WHERE subject_id = ? and" +
						" doctor_id = ? and booking_date = ? and am_pm_ind = ?");
				ps.setString(1, subject_id);
				ps.setString(2, doctor_id);
				ps.setDate(3, (java.sql.Date) booking_date);
				ps.setString(4, am_pm_ind);
				
				ResultSet rs = ps.executeQuery();

				if (rs.next()) {
					if (rs.getString("max_ticket")!=null)
						next_ticket_num = Integer.valueOf(rs.getString("max_ticket")).intValue() + 1;
				}

			} finally {
				ps.close();
			}
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return next_ticket_num;
		
	}

	public int getNextBookingNum() {
		int next_booking_num =1 ;
		try {
			Connection conn = mds.getConnection();
			PreparedStatement ps = null;
			try {
				ps = conn.prepareStatement("SELECT max(booking_id) as max_booking FROM BOOKING");
				
				ResultSet rs = ps.executeQuery();

				if (rs.next()) {
					if (rs.getString("max_booking")!=null)					
						next_booking_num = Integer.valueOf(rs.getString("max_booking")).intValue() + 1;
				}

			} finally {
				ps.close();
			}
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return next_booking_num;
		
	}

	
	
}
